//定义用户相关的仓库
import { defineStore } from "pinia";
//引入获取验证码的请求方法
import { reqSignup, reqLogin } from "@/api/index.js";
import { GET_TOKEN, SET_TOKEN, REMOVE_TOKEN } from "@/utils/user";
const useUserStore = defineStore("User", {
  state: () => {
    return {
      userInfo: JSON.parse(GET_TOKEN()) || {},
    };
  },
  actions: {
    //用户注册的方法
    async userSignup({ username, password, re_password, id_card, image_url}) {
      //注册请求
      const result = await reqSignup({ username,password, re_password,id_card,image_url });
      if (result.code == 1000) {
        return "ok";
      } else {
        return Promise.reject(new Error(result.msg));
      }
    },
    //用户登录的方法
    async userLogin({ username, password ,id_card,image_url}) {
      //登录请求
      const result = await reqLogin({ username, password,id_card,image_url });
      if (result.code == 1000) {
        this.userInfo = result.data;
        //本地存储持久化存储用户信息
        SET_TOKEN(JSON.stringify(this.userInfo));
        //保证当前async函数返回一个成功的promise函数
        return "ok";
      } else {
        return Promise.reject(new Error(result.msg));
      }
    },
    //退出登录方法
    logout() {
      //清空仓库的数据
      this.userInfo = { username: "", token: "" };
      //清空本地存储的数据
      REMOVE_TOKEN();
    },
  },
  getters: {},
});

export default useUserStore;
